package connexion;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;

import parameters.StaticParameters;



public class IncomingMessageReader implements Runnable {
	ObjectInputStream in;
	
	
	Queue<Message>messagesGot=new LinkedList<Message>();
	
	public IncomingMessageReader(ObjectInputStream objectInputStream) {
		in=objectInputStream;
		Thread t=new Thread(this);
		t.start();
	}
	
	public void readMessages()
	{

		while(true)
		{
			Message message=null;
			try {

				message = (Message)in.readObject();
				synchronized (messagesGot) {
					messagesGot.add(message);
					messagesGot.notifyAll();
				}

			} catch (IOException e) {
				e.printStackTrace();
				System.exit(0);
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(StaticParameters.IMR_VERBOSITY)
			System.out.println("IMR>" + message);
		}
	}

	@Override
	public void run() {
		readMessages();
	}
	
	public Queue<Message> getMessages() {
		Queue<Message>incoming=new LinkedList<Message>();
		synchronized (messagesGot) {
			incoming.addAll(messagesGot);
			messagesGot.clear();
		}
		return incoming;
	}

	public Object readFirst() {
		synchronized (messagesGot) {
			while(messagesGot.isEmpty())
				try {
					messagesGot.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			return messagesGot.poll();
		}
	}
}
